<?php

namespace plugin\ycMassage\app\api\controller;

use app\common\manager\SettingsMgr;
use app\common\service\UploadService;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;
use plugin\ycFlyingChess\utils\WechatHelper;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageUserChannels;
use plugin\ycMassage\app\model\MassageUserSalesman;
use plugin\ycMassage\app\model\MassageUserSalesmanStatistics;
use plugin\ycMassage\app\validate\MassageUserSalesman as ValidateMassageUserSalesman;
use plugin\ycMassage\utils\enum\Examine;
use plugin\ycMassage\utils\enum\NoticeType;
use plugin\ycMassage\utils\enum\State;
use plugin\ycMassage\utils\notice\Notice;
use support\Request;
use think\facade\Db;
use think\facade\Env;

class SalesmanController extends BaseController
{
    protected $noNeedAppid = ['qrcode'];
    protected $noNeedLogin = ['qrcode'];
    public function user(Request $request)
    {
        $model = MassageUserSalesman::where(['uid' => $request->uid, 'saas_appid' => $request->saas_appid])->find();
        if ($model) {
            return $this->successRes($model);
        }
        return $this->fail('未找到渠道商申请信息');
    }
    public function list(Request $request)
    {
        $page = (int)$request->get('page');
        $limit = (int)$request->get('limit', 20);
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        $where = [
            ['a.salesman_uid', '=', $uid],
            ['a.saas_appid', '=', $saas_appid]
        ];
        $action = $request->get('action');
        if ($action == 'empty') {
            $where[] = ['a.uid', '=', NULL];
        } else {
            $where[] = ['a.uid', 'NOT NULL', NULL];
        }
        $domain = getHpConfig('domain', (int)$request->saas_appid, 'plugins_domains');
        $data = MassageUserChannels::where($where)
            ->alias('a')
            ->join('massage_user u', 'u.id=a.uid', 'LEFT')
            ->join('massage_user_channels_category c', 'c.id=a.category_id', 'LEFT')
            ->order('a.id desc')
            ->field('a.*,u.nickname,u.headimg,c.title as category_name')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) use ($domain) {
                if ($item->uid) {
                    $item->nickname = base64_decode($item->nickname);
                    if (strpos($item->headimg, 'http') !== 0) {
                        $item->headimg = UploadService::url($item->headimg);
                    }
                }
                if ($item->expire_time) {
                    if ($item->expire_time < date('Y-m-d H:i:s')) {
                        $item->expire_time = '已到期';
                    }
                } else {
                    $item->expire_time = '永久';
                }
                $item->commission_text = $item->commission > 0 ? $item->commission . '%' : '系统设置';
                $item->platform_commission_text = $item->platform_commission > 0 ? $item->platform_commission . '%' : '系统设置';
                $url = $domain . "/app/ycMassage/api/Salesman/qrcode?id=" . $item->id . "&saas_appid=" . $item->saas_appid;
                $item->poster = $url;
            });
        return $this->successRes($data);
    }
    public function apply(Request $request)
    {
        $D = $request->post();
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        $validate = new ValidateMassageUserSalesman;
        if (!$validate->check($D)) {
            return $this->fail($validate->getError());
        }
        Db::startTrans();
        try {
            $model = MassageUserSalesman::where(['uid' => $request->uid, 'saas_appid' => $saas_appid])->find();
            if (!$model) {
                $model = new MassageUserSalesman;
                $model->uid = $uid;
                $model->saas_appid = $saas_appid;
            }
            $model->mobile = $D['mobile'];
            $model->title = $D['title'];
            $model->province_id = (int)$D['province_id'];
            $model->province = $D['province'];
            $model->city_id = (int)$D['city_id'];
            $model->city = $D['city'];
            $model->area_id = (int)$D['area_id'];
            $model->area = $D['area'];
            $model->examine = Examine::WAIT['value'];
            $model->state = State::NO['value'];
            $model->remark = $D['remark'];
            $model->save();
            $notice = new Notice();
            $notice->saas_appid = $model->saas_appid;
            $notice->role = ['ADMIN'];
            $notice->type = NoticeType::WORK_ORDER['value'];
            Db::commit();
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
        $notice->setData([
            'service_name' => '业务员申请审核',
            'name' => $model->title,
            'time' => date('Y-m-d H:i:s'),
        ]);
        $notice->send();
        return $this->success('申请成功,请等待审核');
    }
    public function statistics(Request $request)
    {
        $date = $request->get('date');
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        $model = MassageUserSalesmanStatistics::where(['uid' => $uid, 'saas_appid' => $saas_appid]);
        switch ($date) {
            case 'yesterday':
                $model->whereDay('create_time', 'yesterday');
                break;
            case 'week':
                $model->whereWeek('create_time');
                break;
            case 'month':
                $model->whereMonth('create_time');
                break;
            case 'last_month':
                $model->whereMonth('create_time', 'last month');
                break;
            default:
                $model->whereDay('create_time');
                break;
        }
        $MassageUserSalesmanStatistics = $model->select();
        $data = [
            'order_num' => 0,
            'order_price' => 0,
            'duration' => 0,
            'commission' => 0,
            'empty_channels' => 0,
            'channels' => 0,
        ];
        $data['channels'] = MassageUserChannels::where(['salesman_uid' => $uid, 'saas_appid' => $saas_appid])->whereNotNull('uid')->count();
        $data['empty_channels'] = MassageUserChannels::where(['salesman_uid' => $uid, 'saas_appid' => $saas_appid])->whereNull('uid')->count();
        foreach ($MassageUserSalesmanStatistics as $item) {
            $data['order_num'] += $item->order_num;
            $data['order_price'] += $item->order_price;
            $data['duration'] += $item->duration;
            $data['commission'] += $item->commission;
            // $data['browse_num'] += $item->browse_num;
        }
        return $this->successRes($data);
    }
    public function createEmptyQrcode(Request $request)
    {
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        $num = (int)$request->post('num');
        $empty_channels = MassageUserChannels::where(['salesman_uid' => $uid, 'saas_appid' => $saas_appid])->whereNull('uid')->count();
        if ($empty_channels > 99) {
            return $this->fail('空码数量不能超过100个');
        }
        $num = $num > $empty_channels ? $num - $empty_channels : $num;
        Db::startTrans();
        try {
            for ($i = 0; $i < $num; $i++) {
                $model = new MassageUserChannels;
                $model->salesman_uid = $uid;
                $model->saas_appid = $saas_appid;
                $model->state = State::NO['value'];
                $model->examine = Examine::WAIT['value'];
                $model->save();
            }
            Db::commit();
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
        return $this->success('生成成功');
    }
    public function qrcode(Request $request)
    {
        $channels_id = $request->get('id');
        $saas_appid = $request->get('saas_appid');
        $model = MassageUserChannels::where(['id' => $channels_id, 'saas_appid' => $saas_appid])->find();
        if (!$model) {
            return $this->fail('未找到渠道商信息');
        }
        $domain = getHpConfig('domain', (int)$saas_appid, 'plugins_domains');
        if ($model->uid) {
            $channels = getHpConfig('', $saas_appid, 'channels');
            $valid_time = 0;
            if (isset($channels['valid_time'])) {
                $valid_time = $channels['valid_time'];
            }
            $url = $domain . "/app/ycMassage/#/pages/index/index?appid={$saas_appid}&channels_id={$channels_id}&valid_time={$valid_time}";
        } else {
            $url = $domain . "/app/ycMassage/Salesman/index?id=" . $model->id;
        }
        $builder = Builder::create()
            ->writer(new PngWriter())
            ->writerOptions([])
            ->data($url)
            ->encoding(new Encoding('UTF-8'))
            ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
            ->size(1024)
            ->margin(10)
            ->roundBlockSizeMode(new RoundBlockSizeModeMargin())
            ->validateResult(false)
            ->labelText('ID:'.$model->id);
        $result = $builder->build();
        return response($result->getString(), 200, ['Content-Type' => 'image/png', 'content-disposition' => 'attachment; filename="qrcode-' . $model->id . '.png"']);
    }
}
